var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

Page({
  data: {
    id: 0,
    product: {},
    attribute: [],
    issueList: [],
    comment: [],
    brand: {},
    specificationList: [],
    productList: [],
    relatedGoods: [],
    cartCount: 0,
    userHasCollect: 0,
    number: 1,
    checkedSpecText: '规格数量选择',
    // tmpSpecText: '请选择规格数量',
    checkedSpecPrice: 0,
    openAttr: false,
    openShare: false,
    noCollectImage: '/static/images/icon_collect.png',
    hasCollectImage: '/static/images/icon_collect_checked.png',
    collectImage: '/static/images/icon_collect.png',
    shareImage: '',
    soldout: false,
    canWrite: false, //用户是否获取了保存相册的权限
  },

  // 页面分享
  onShareAppMessage: function() {
    let that = this;
    return {
      title: that.data.product.name,
      desc: '唯爱与海鲜不可辜负',
      path: '/pages/product/product?id=' + this.data.id
    }
  },

  shareFriendOrCircle: function() {
    //var that = this;
    if (this.data.openShare === false) {
      this.setData({
        openShare: !this.data.openShare
      });
    } else {
      return false;
    }
  },
  handleSetting: function(e) {
    var that = this;
    // console.log(e)
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '不授权无法保存',
        showCancel: false
      })
      that.setData({
        canWrite: false
      })
    } else {
      wx.showToast({
        title: '保存成功'
      })
      that.setData({
        canWrite: true
      })
    }
  },
  // 保存分享图
  saveShare: function() {
    let that = this;
    wx.downloadFile({
      url: that.data.shareImage,
      success: function(res) {
        console.log(res)
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res) {
            wx.showModal({
              title: '存图成功',
              content: '图片成功保存到相册了，可以分享到朋友圈了',
              showCancel: false,
              confirmText: '好的',
              confirmColor: '#a78845',
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                }
              }
            })
          },
          fail: function(res) {
            console.log('fail')
          }
        })
      },
      fail: function() {
        console.log('fail')
      }
    })
  },
  // 获取商品信息
  getProductInfo: function() {
    let that = this;
    util.request(api.ProductDetail, {
      productId: that.data.id
    }).then(function(res) {
      if (res.code === 0) {
        let product = res.data.info;
        product.gallery = JSON.parse(product.gallery);
        that.setData({
          product: product,
          userHasCollect: res.data.userHasCollect,
          // shareImage: res.data.shareImage,
          checkedSpecPrice: product.retailPrice,
          collectImage: res.data.userHasCollect == 0 ? that.data.noCollectImage : that.data.hasCollectImage
          // groupon: res.data.groupon
        });
        WxParse.wxParse('goodsDetail', 'html', res.data.info.detail, that);
      }
    });
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.getProductInfo();
    }
    let that = this;
    wx.getSetting({
      success: function(res) {
        console.log(res)
        //不存在相册授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: function() {
              that.setData({
                canWrite: true
              })
            },
            fail: function(err) {
              that.setData({
                canWrite: false
              })
            }
          })
        } else {
          that.setData({
            canWrite: true
          });
        }
      }
    })
  },
  onShow: function() {
    // 页面显示
    var that = this;
    util.request(api.CartProductCount).then(function(res) {
      if (res.code === 0) {
        that.setData({
          cartCount: res.data
        });
      }
    });
    // this.setData({
    //   id: 3
    // });
    // this.getProductInfo();
  },
  //立即购买（先自动加入购物车）
  addFast: function() {
    var that = this;
    //立即购买
    util.request(api.CartFastAdd, {
        number: this.data.number,
        productId: this.data.id
      }, "POST")
      .then(function(res) {
        if (res.code == 0) {
          // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
          try {
            wx.setStorageSync('cartIds', res.data);
            wx.navigateTo({
              url: '/pages/order/checkout/checkout'
            })
          } catch (e) {}

        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.msg,
            mask: true
          });
        }
      });
  },

  //添加到购物车
  addToCart: function() {
    var that = this;
    //添加到购物车
    util.request(api.CartAdd, {
        number: this.data.number,
        productId: this.data.id
      }, "POST")
      .then(function(res) {
        if (res.code == 0) {
          wx.showToast({
            title: '添加成功'
          });
          let cartCount = res.data;
          that.setData({
            cartCount: cartCount
          });
          app.globalData.cartCount = cartCount;
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: res.msg,
            mask: true
          });
        }
      });
  },
  //添加或是取消收藏
  addCollectOrNot: function() {
    let that = this;
    util.request(api.CollectAddOrDelete, {
      type: 0,
      valueId: this.data.id
    }, "POST").then(function(res) {
      if (that.data.userHasCollect == 1) {
        that.setData({
          collectImage: that.data.noCollectImage,
          userHasCollect: 0
        });
      } else {
        that.setData({
          collectImage: that.data.hasCollectImage,
          userHasCollect: 1
        });
      }
    });
  },
  switchAttrPop: function() {
    if (this.data.openAttr == false) {
      this.setData({
        openAttr: !this.data.openAttr
      });
    }
  },
  closeAttr: function() {
    this.setData({
      openAttr: false,
    });
  },
  closeShare: function() {
    this.setData({
      openShare: false,
    });
  },
  openCartPage: function() {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },
  onReady: function() {
    // 页面渲染完成

  }

})